<!DOCTYPE html>
<html lang="en">
<head>
    <title>Xterm</title>
    <link rel="stylesheet" href="/main.css"/>
    <link rel="stylesheet" href="/xterm/css/xterm.css"/>

</head>
<body>
<div id="xterm"></div>


<script src="xterm/lib/xterm.js" ></script>
<script>
    var term;
    // var websocket = new WebSocket("ws://" + window.location.hostname + ":" + window.location.port + "/term");
    var websocket = new WebSocket("ws://192.168.80.20:3000/term");
    console.log( window.location.hostname)
    console.log( window.location.port)
    websocket.binaryType = "arraybuffer";

    function buf2str(buffer) {
        let encodedString = String.fromCodePoint.apply(null, new Uint8Array(buffer));
        let decodedString = decodeURIComponent(escape(encodedString));//没有这一步中文会乱码
        return decodedString
    }

    websocket.onopen = function (evt) {
        term = new Terminal({
            screenKeys: true,
            useStyle: true,
            cursorBlink: true,
            cursorStyle: 'underline', // 光标样式
            theme: {
                foreground: '#7e9192', // 字体
                background: '#002833', // 背景色
                cursor: 'help', // 设置光标
                lineHeight: 16
            }
        });


        term.prompt = () => {
            term.writeln('Welcome!')
            term.writeln('请不要进行危险操作')
        }
        term.prompt()
        term.onData(function (data) {
            websocket.send(new TextEncoder().encode("\x00" + data));
        })


        term.onResize(function (evt) {

            websocket.send(new TextEncoder().encode("\x01" + JSON.stringify({cols: evt.cols, rows: evt.rows})))
        });


        term.open(document.getElementById('xterm'));

        websocket.onmessage = function (evt) {
            if (evt.data instanceof ArrayBuffer) {
                term.write(buf2str(evt.data));
            } else {
                alert(evt.data)
            }
        }

        websocket.onclose = function (evt) {
            term.write("Session terminated");
            term.destroy();
        }

        websocket.onerror = function (evt) {
            if (typeof console.log == "function") {
                console.log(evt)
            }
        }
    }
</script>
</body>
</html>
